package org.test;

import java.io.File;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.tools.JavaCompiler;
import javax.tools.JavaFileObject;
import javax.tools.StandardJavaFileManager;
import javax.tools.ToolProvider;

public class JavaCompileUtil {

	public static boolean compile(Collection<File> javaSourceFile, String targetPath) {
		String java_version = System.getProperty("java.specification.version");
		JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
		List<String> opts = new ArrayList<String>();
		opts.add("-target");
		opts.add(java_version);
		opts.add("-encoding");
		opts.add("UTF-8");
		opts.add("-d");
		opts.add(targetPath);
		opts.add("-classpath");
//		opts.add();
		StandardJavaFileManager manager = compiler.getStandardFileManager(null, null, null);
		Iterable<? extends JavaFileObject> files = manager.getJavaFileObjects(javaSourceFile.toArray(new File[0]));
		JavaCompiler.CompilationTask task = compiler.getTask(null, manager, null, opts, null, files);
		return task.call();
	}

	public static Collection<File> findSubFileByExtName(String codeDir, String extName) {
		extName = "." + extName.toLowerCase();
		Set<File> javaFiles = new HashSet<File>();
		FileIterator it = new FileIterator(codeDir);
		while (it.hasNext()) {
			File file = it.next();
			if (file.isFile() && file.getName().toLowerCase().endsWith(extName)) {
				javaFiles.add(file);
			}
		}
		return javaFiles;
	}

}
